<template>
  <div>

    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="150px" class="demo-ruleForm" :size="formSize"
      status-icon>
      <el-row class="custom-row" :gutter="20">
        <el-col :span="5">
          <el-form-item label="提交人" prop="userName">
            <el-input class="elFormItem100PX" v-model="ruleForm.userName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="单据日期" prop="createTime">
            <el-date-picker v-model="ruleForm.createTime" type="date" placeholder="Pick a date" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="单据编号" prop="salesCode">
            <el-input class="elFormItem100PX" v-model="ruleForm.salesCode" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row class="custom-row" :gutter="20">
        <el-col :span="5">
          <el-form-item label="客户名称" prop="custName">
            <el-select v-model="ruleForm.custName" filterable @click="on_getCustName" :filter-method="getCustName"
              class="elFormItem100PX">
              <el-option v-for="item in optionsCustName" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="5">
          <el-form-item label="付款方式" prop="paymentMethod">
            <el-input class="elFormItem100PX" v-model="ruleForm.paymentMethod" />
          </el-form-item>
        </el-col>


        <el-col :span="5">
          <el-form-item label="客户联系方式" prop="custPhone">
            <el-input class="elFormItem100PX" v-model="ruleForm.custPhone" />
          </el-form-item>
        </el-col>

        <el-col :span="5">
          <el-form-item label="项目类型" prop="projectType">
            <el-select v-model="ruleForm.projectType" class="elFormItem100PX" placeholder="项目类型">
              <el-option label="WMS" value="WMS" />
              <el-option label="MES" value="MES" />
              <el-option label="AGV" value="AGV" />
              <el-option label="SCADA" value="SCADA" />
              <el-option label="SAP" value="SAP" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- 
      <el-col :span="5">
        <el-form-item label="订单状态" prop="state">
          <el-select v-model="ruleForm.state" class="elFormItem100PX" placeholder="项目类型">
            <el-option label="跟踪中" :value=1 />
            <el-option label="丢单" :value=2 />
            <el-option label="客户取消" :value=3 />
            <el-option label="已签订" :value=4 />
          </el-select>
        </el-form-item>
      </el-col> -->
      </el-row>



      <el-row class="custom-row" :gutter="20">

        <el-col :span="20">
          <el-form-item label="施工地址" prop="custAddress">
            <el-input class="elFormItem100PX" v-model="ruleForm.custAddress" autosize type="textarea"
              placeholder="Please input" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row class="custom-row" :gutter="20">
        <el-col :span="5">
          <el-form-item label="数量" prop="number">
            <el-input class="elFormItem100PX" v-model="ruleForm.number" type="number" />
          </el-form-item>
        </el-col>

        <el-col :span="5">
          <el-form-item label="含税金额（万元）" prop="amount">
            <el-input class="elFormItem100PX" v-model="ruleForm.amount" type="number" />
          </el-form-item>
        </el-col>

        <el-col :span="10">
          <el-form-item label="销售预测单" prop="salesForecastCode">
            <el-select v-model="ruleForm.salesForecastCode" filterable @click="on_getSalesforecast"
              :filter-method="getSalesforecast" class="elFormItem100PX" style="width: 100%;">
              <el-option v-for="item in optionsonSalesforecast" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>

      <el-row class="custom-row" :gutter="20">
        <el-col :span="5">
          <el-form-item label="要求施工时间" prop="strTime">
            <el-date-picker v-model="ruleForm.strTime" type="date" placeholder="Pick a date" />
          </el-form-item>
        </el-col>

        <el-col :span="5">
          <el-form-item label="要求结束时间" prop="endTime">
            <el-date-picker v-model="ruleForm.endTime" type="date" placeholder="Pick a date" />
          </el-form-item>
        </el-col>


        <el-col :span="5">
          <el-form-item label="实际结束日期" prop="actualEndTime">
            <el-date-picker v-model="ruleForm.actualEndTime" type="date" placeholder="Pick a date" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row class="custom-row" :gutter="20">

        <el-col :span="5">
          <el-form-item label="跟踪状态" prop="trackingState">
            <el-input class="elFormItem100PX" v-model="ruleForm.trackingState" autosize type="textarea"
              placeholder="Please input" />
          </el-form-item>
        </el-col>

        <el-col :span="5">
          <el-form-item label="备注" prop="remark">
            <el-input class="elFormItem100PX" v-model="ruleForm.remark" autosize type="textarea"
              placeholder="Please input" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          提交
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">清除</el-button>
      </el-form-item>
    </el-form>
    <div>
      <div :key="salesHistoryState">
        <history :param="route.params.salesCode" />
      </div>
    </div>
  </div>
</template>
<style>
.elFormItem100PX {
  min-width: 200px;
}

.custom-row {
  margin-bottom: 20px;
  /* 或者使用 padding-bottom */
}
</style>
<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import api from '/@/api/sy/apiERP.js';
import { v } from 'vxe-table';
// 历史纪录，单独子页面
import history from '/@/views/erp/sales/sales_upd_history.vue';

import { useRoute, useRouter } from "vue-router";
// 路由跳转到其他指定页面
const router = useRouter();

// 接收动态路由跳转传参
const route = useRoute();


interface RuleForm {
  salesID: number | null,
  salesForecastCode: number | null,
  salesCode: string | null,
  projectType: string | null,
  custName: string | null,
  custPhone: string | null,
  custAddress: string | null,
  number: number | null,
  amount: number | null,
  paymentMethod: string | null,
  remark: string | null,
  userName: number | null,
  updName: number | null,
  state: number | null,
  updateTime: Date | null,
  createTime: Date | null,
  strTime: Date | null,
  endTime: Date | null,
  actualEndTime: Date | null,

  trackingState: string | null

}


//历史记录刷新
var salesHistoryState = ref(0)

interface ListItem {
  label: string,
  value: string | null | number
}
const options2 = ref<ListItem[]>([])
function on_optCustName2(query: string) {
  if (query == 'a') {
    options2.value = [{
      value: 'Option1',
      label: 'Option1',
    },]
  } else {
    options2.value = [
      {
        value: 'Option2',
        label: 'Option2',
      },]
  }
}


const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
let ruleForm = ref<RuleForm>({
  salesID: null,
  salesForecastCode: null,
  salesCode: null,
  projectType: null,
  custName: null,
  custPhone: null,
  custAddress: null,
  number: null,
  amount: null,
  paymentMethod: null,
  remark: null,
  userName: null,
  updName: null,
  state: null,
  updateTime: null,
  createTime: null,
  strTime: null,
  endTime: null,
  actualEndTime: null,
  trackingState: null,
})


var optionsCustName = ref<ListItem[]>()
var optionsonSalesforecast = ref<ListItem[]>()

const rules = reactive({
  salesCode: [
    { required: true, message: '编号不可为空', trigger: 'blur' },
    // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  projectType: [
    {
      // type: 'array',
      required: true,
      message: '请至少选一个类型',
      trigger: 'change',
    },
  ],
  state: [
    {
      // type: 'number',
      required: true,
      message: '请至少选一个类型',
      trigger: 'change',
    },
  ],
  custName: [
    {
      required: true,
      message: '客户名称',
      trigger: 'change',
    },
  ],
  custPhone: [
    {
      required: true,
      message: '客户联系方式',
      trigger: 'change',
    },
  ],
  // estimatedStartTime: [
  //   {
  //     type: 'date',
  //     required: true,
  //     message: '请填写正确的时间',
  //     trigger: 'change',
  //   },
  // ],
  amount: [
    {
      required: true,
      message: '金额需要填写',
      trigger: 'blur'
    },
  ],
})
var re_optCustName = [
  {
    value: 'Option5',
    label: 'Option5',
  },
]
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      addSales(formEl)
    } else {
    }
  })
}
interface Option {
  label: string;
  value: string;
}

function on_getCustName() {
  getCustName('')
}
function on_getSalesforecast() {
  getSalesforecast('')
}

function getSalesforecast(query: any) {

  api.post('public/sales/salesADD_getSalesForecastList', query, {
    headers: {
      'Content-Type': 'text/plain', // 设置请求体的类型为纯文本
    },
  }).then((response: any) => {
    optionsonSalesforecast.value = []
    var s = <RuleForm[]>response.data.data
    for (const a of s) {
      optionsonSalesforecast.value?.push({ label: a.salesCode + "——" + a.custName, value: a.salesCode })
    }
    // 处理服务器返回的响应
  })
    .catch((error: any) => {

      //console.log(error);
      // 处理错误
    })
    .finally(() => {
      // console.log('必须执行')
    })
}

function getCustName(query: any) {
  api.post('public/sales/salesForecastADD_getCustName', query, {
    headers: {
      'Content-Type': 'text/plain', // 设置请求体的类型为纯文本
    },
  }).then((response: any) => {
    optionsCustName.value = []
    for (const a of response.data.data) {
      optionsCustName.value?.push({ label: a, value: a })
    }


    var ab = optionsCustName.value.some(option => option.label === query)
    // console.log((ab));
    if (!ab && query.length > 0) {
      optionsCustName.value?.push({ label: (query + '(该客户不存在，可强制选择)'), value: query })
    }

    // 处理服务器返回的响应
  })
    .catch((error: any) => {

      //console.log(error);
      // 处理错误
    })
    .finally(() => {
      // console.log('必须执行')
    })

}



function on_optCustName(query: any, option: any) {
  // 自定义过滤逻辑，这里示例为选项的 label 字段的模糊匹配
  optionsCustName.value = [{ label: 'a', value: '1' }]
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))



function addSales(formEl: FormInstance | undefined) {
  var param = ruleForm.value
  api.post('public/sales/updSales', param).then((response: any) => {
    // 处理服务器返回的响应
    if (response.data.code == 200) {
      alert('保存成功')
    }
  })
    .catch((error: any) => {
      //console.log(error);
      // 处理错误
    })
    .finally(() => {
      salesHistoryState.value = salesHistoryState.value+1
      getSales()
    })

    ;
}

function getSales() {

  api.post('public/sales/getSales', ruleForm.value).then((response: any) => {
    // 处理服务器返回的响应
    if (response.data.data != null) {
      ruleForm.value = response.data.data
    } else {
      alert("没有找到此编号")
      router.push({ name: "sales_show" });
    }
  })
    .catch((error: any) => {
      //console.log(error);
      // 处理错误
    })
    .finally(() => {
    })

    ;
}

onMounted(async () => {
  console.log(route.params)

  // name 值为路由中的 name
  if (route.params.salesCode.length > 0) {
    ruleForm.value.salesCode = <string>route.params.salesCode
    console.log(ruleForm);

    getSales()
  } else {
    alert("参数为空")
    router.push({ name: "sales_show", });
  }
  // 在这里写逻辑
});
</script>
